from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from .models import *
import hashlib
from django.core.mail import send_mail
from django.conf import settings
from . import task, user_decoration
from goods.models import GoodsInfo
from cart.models import CartInfo
from order.models import OrderDetailInfo, OrderInfo
from django.core.paginator import Paginator,Page



# Create your views here.

#显示用户注册页面
def register(request):

    context = {'title':'注册','topline':2}
    return render(request, 'user/register.html', context)

#验证用户名是否已经被占用
#用的是ajax
def check(request):
    # print(user)
    name = request.GET.get('name')
    count = UserInfo.objects.filter(uname=name).count()

    return JsonResponse({'count':count})

#处理用户注册信息
def register_handle(request):
    dict = request.POST
    name = dict.get('user_name')
    email = dict.get('email')
    pwd = dict.get('pwd')
    #将密码进行sha1加密
    pwd = hashlib.sha1(pwd.encode()).hexdigest()
    # print(name,email,pwd)

    #将数据存入表中
    user = UserInfo()
    user.uname = name
    user.upwd = pwd
    user.email = email
    user.isActive = True  #todo 这句先将注册的用户一次性生成
    user.save()

    # msg = '<a href="http://127.0.0.1:8000/user/register_active/?id=%d">点击激活</a>' % user.id
    # send_mail("注册激活", '', settings.EMAIL_FROM, [user.email, ], html_message=msg)
    # 异步实现发送邮箱,如果不用delay发现确实不行
    task.celery_sendmail.delay(user)

    return HttpResponse('请验证邮箱')



#处理邮箱激活信息
def register_active(request):
    user_id = request.GET.get('id')
    user = UserInfo.objects.filter(id=user_id)
    # user1 = UserInfo.objects.get(id=user_id)
    # print(user.count())
    if user.count() == 0:
        return HttpResponse('没有此用户')
    # print(user[0])
    # 为什么save不了???,必须要调用一下才可以,因为用的是查询集
    reuser = user[0]
    reuser.isActive = True
    reuser.save()
    # user.isActive = True
    # user.save()
    # print(type(user[0]))
    # print(type(user1))
    # if(user[0] == user1):
    #     print(True)
    # else:
    #     print(False)

    #注册成功跳转到首页
    return redirect('/')



#登陆页
def login(request):
    #如果设置了记录用户名,那么就显示
    name = request.COOKIES.get('ttsx_user','')
    context = {'user':name,'title':'登陆','topline':2}  #注意这里的user跟login_handle中的user是一致的

    return render(request, 'user/login.html', context)


#登陆处理
def login_handle(request):
    try:
        dict = request.POST
        name = dict.get('username')
        # user = request.COOKIES.get('ttsx_user','')  #没有,则给一个默认值
        pwd = dict.get('pwd')
        checkbox = dict.get('checkbox')
        print(checkbox)  # 如果没获得,则为None,如果获得,则为1
        pwd = hashlib.sha1(pwd.encode()).hexdigest()

        # print(name, pwd)

        context = {'user_error': 0, 'pwd_error': 0, 'user': name, 'title': '登陆', 'topline': 2}

        # todo get只能得到一个值,如果没有值或者多个值就报错
        # user = UserInfo.objects.get(uname=name)
        user = UserInfo.objects.filter(uname=name, isActive=True, isDelete=False)

        # 判断用户名
        if user.count() == 0:
            # return HttpResponse('没有此用户')
            context['user_error'] = 1
            response = render(request, 'user/login.html', context)
        else:
            reuser = user[0]
            repwd = reuser.upwd
            reactive = reuser.isActive
            # if pwd != repwd or reactive==False:  #这句是为了测试是否激活状态
            if pwd != repwd:
                context['pwd_error'] = 1
                response = render(request, 'user/login.html', context)
            else:
                # 登陆成功
                # todo 设置登陆记录,配置到session服务器
                request.session['uid'] = reuser.id
                request.session['uname'] = reuser.uname



                # 登陆成功,则返回到原先的url,这里的url定义在中间件
                response = redirect(request.session.get('url', '/'))
                if checkbox:
                    response.set_cookie('ttsx_user', name, expires=60 * 60 * 24 * 7)
                else:
                    response.set_cookie('ttsx_user', '', expires=-1)
                cart = CartInfo.objects.filter(user_id=reuser.id)
                cart_num = 0
                for i in cart:
                    cart_num += i.count
                response.set_cookie('cart_num',cart_num)

        return response
    except Exception:
        return redirect('/user/login/')






#退出
def logout(request):
    #将session里面存储的用户清除
    request.session.flush()

    response = redirect(request.session.get('url', '/'))  #todo这里会出问题
    response.set_cookie('cart_num', 0)
    #todo
    return response


@user_decoration.islogin
#用户中心-个人中心
def user_center(request):
    # 这个页面需要显示用户名和邮箱,就是注册的信息.
    # 这个信息来自于登陆后的状态保持.所以登陆后设置一个登陆id
    uid = request.session.get('uid') #默认为0
    user = UserInfo.objects.get(id=uid)

    histroy =request.COOKIES.get('history','')
    if histroy:
        histroy_list = histroy.split('&')
        histroy_goods = []
        for i in histroy_list:
            i = int(i)
            histroy_good = GoodsInfo.objects.get(id=i)
            histroy_goods.append(histroy_good)
    else:
        histroy_goods = []

    context = {'title': '个人中心', 'user': user, 'histroy_goods':histroy_goods}
    return render(request, 'user/user_center_info.html', context)
    # if uid:
    #     user = UserInfo.objects.get(id=uid)
    #     context = {'title':'个人中心', 'user':user}
    #     return render(request, 'user/user_center_info.html', context)
    # else:
    #     return redirect('/user/login/')


@user_decoration.islogin
#收货地址
def center_site(request):
    uid = request.session.get('uid')  # 默认为0
    user = UserInfo.objects.get(id=uid)
    fulladdr = AddressInfo.objects.filter(user_id=uid)
    context = {'title':'收货地址', 'user':user, 'fulladdr':fulladdr}
    return render(request, 'user/user_center_site.html', context)

@user_decoration.islogin
#增加收货信息
def add_user_site(request):
    uid = request.session.get('uid')  # 默认为0
    # print(uid)
    try:

        # 通过post请求获得添加的收货人信息
        dict = request.POST
        # 收件人
        sjr = dict.get('sjr')
        # 手机
        sjh = dict.get('sjh')

        # 省id
        shengid = dict.get('sheng')
        # sheng = AreaInfo.objects.get(id=shengid)
        # 市id
        shiid = dict.get('shi')
        # 区id
        quid = dict.get('qu')
        # 简短地址
        short_addr = dict.get('short_addr')
        print(sjr,sjh,shengid,shiid,quid,short_addr)
        # 得到完整地址
        area = AreaInfo.objects
        sheng = area.get(id=shengid)
        shi = area.get(id=shiid)
        qu = area.get(id=quid)
        addr = '%s %s %s %s ' % (sheng.atitle, shi.atitle, qu.atitle, short_addr)

        print(addr)

        addressinfo = AddressInfo()
        addressinfo.sjr = sjr
        addressinfo.sjh = sjh
        addressinfo.sheng = shengid
        addressinfo.shi = shiid
        addressinfo.qu = quid
        addressinfo.addr = addr
        # 获取外键
        uid = request.session.get('uid')  # 默认为0
        addressinfo.user_id = uid
        # 保存数据库
        addressinfo.save()


    except Exception:
        context = {'alertimg':'信息不完全,无法保存,请重试','alert':1}

    else:
        context = {'alertimg':'保存成功','alert':1}
        print("保存成功")
    return redirect('/user/center_site/')



#返回省市区信息
def return_area(request):
    dict = request.GET
    #模板传过来的id,默认为空
    aParentId = dict.get('id',None)

    # print(aParentId,'------------------------------')
    arealist = AreaInfo.objects.filter(aParent=aParentId)
    # print(arealist)
    returnlist = []
    for i in arealist:
        d = {}
        d['id'] = i.id
        d['atitle'] = i.atitle
        returnlist.append(d)

    returndict = {'returnlist':returnlist}  #{'returnlist':[{i.id:i.atitle},{i.id:i.atitle}]}

    return JsonResponse(returndict)




# from django.core.paginator import Page, Paginator


@user_decoration.islogin
# 用户中心的订单信息
def order(request):
    uid = request.session.get('uid')
    #查询用户的订单
    order = OrderInfo.objects.filter(user_id=uid).order_by('-odate')
    # 查询该订单的所有商品详情页
    # orderdetail = order.orderdetailinfo_set.all()

    #进行分页,每页显示两个
    paginator = Paginator(order, 2)

    pageindex = request.GET.get('page',1)
    #第一页数据
    page = paginator.page(pageindex)



    context = {'title':'用户订单','page':page,}
    return render(request, 'user/user_center_order.html', context)

